package org.example.com.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.com.pojo.House;
import org.example.com.pojo.PageResult;
import org.example.com.pojo.Result;
import org.example.com.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/house")
@Slf4j
public class HouseController {

    @Autowired
    private HouseService houseService;

    /**
     * 获取房源推荐列表
     */
    @GetMapping("/nearbyHouses")
    public Result getNearbyHouses() {
        log.info("获取房源推荐列表");
        List<House> houses = houseService.getNearbyHouses();
        return Result.success(houses);
    }

    /**
     * 获取房源列表(搜索/筛选)
     */
    @GetMapping("/search")
    public Result searchHouses(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String provinceId,
            @RequestParam(required = false) String cityId,
            @RequestParam(required = false) String districtId,
            @RequestParam(required = false) String minRent,
            @RequestParam(required = false) String maxRent,
            @RequestParam(required = false) String paymentType,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) String orderType) {
        
        log.info("搜索房源列表，页码：{}，每页条数：{}，关键词：{}", page, limit, keyword);
        
        PageResult pageResult = houseService.searchHouses(page, limit, keyword, 
                provinceId, cityId, districtId, minRent, maxRent, paymentType, orderBy, orderType);
        
        // 构建返回数据格式
        Map<String, Object> data = new HashMap<>();
        data.put("records", pageResult.getRecords());
        data.put("total", pageResult.getTotal());
        data.put("size", limit);
        data.put("current", page);
        data.put("pages", (pageResult.getTotal() + limit - 1) / limit);
        
        return Result.success(data);
    }

    /**
     * 获取房源详情
     */
    @GetMapping("/detail/{id}")
    public Result getHouseDetail(@PathVariable Integer id) {
        log.info("获取房源详情，ID：{}", id);
        House house = houseService.getHouseDetail(id);
        if (house == null) {
            return Result.error("房源不存在");
        }
        return Result.success(house);
    }

    /**
     * 添加房源
     * @param house
     * @return
     */
    @PostMapping("/add")
    public Result addHouse(@RequestBody House house) {
        log.info("添加房源信息：{}", house);
        houseService.addHouse(house);
        return Result.success();
    }
}
